package com.it.dao.impl;

import com.it.Bean.Admin;
import com.it.dao.AdminDao;
import com.it.db.DBManager;
import com.it.db.JdbcTemplate;
import com.it.mapping.EntityMapping;
import com.it.mapping.MappingFactory;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

public class AdminDaoimpl implements AdminDao {

    public static DBManager dbManager=null;
    public static Connection conn =null;
    public static JdbcTemplate jdbcTemplate=null;
    public static MappingFactory mappingFactory=null;
    public static EntityMapping map=null;
    static{
        //抽取数据库连接信息
        dbManager = DBManager.getInstance();
        //获得数据库连接
        conn = dbManager.getConnection();
        //获取JDBC工具类
        jdbcTemplate = JdbcTemplate.getInstance();
        //设置连接
        jdbcTemplate.setConnection(conn);
        //获取封装类工厂
        mappingFactory = MappingFactory.getInstance();
        //获取封装类
        map = mappingFactory.getMap(MappingFactory.ADMIN_MAPPING);
    }

    @Override
    public Admin queryById(Integer id) {

        //获取结果集
        List<Object> list = jdbcTemplate.query("select  * from admin where id=?", map,id);
        Admin admin = (Admin) list.get(0);
        return admin;
    }

    @Override
    public Admin Login(Admin admin) throws Exception{

        //获取结果集
        List<Object> list = jdbcTemplate.query("select  * from admin where username=? and password=?",
                map,admin.getUsename(),admin.getPassword());
        if (list.size()!=0){
            Admin admin1 = (Admin) list.get(0);
            return admin1;
        } 
        return null;
    }

    @Override
    public List<Admin> getQueryAll() {

        //获取结果集
        List<Object> list = jdbcTemplate.query("select  * from admin", map);
        List<Admin> admins = new ArrayList<>();
        for (Object o : list) {
            admins.add( (Admin) o);

        }
        return admins;
    }

    @Override
    public boolean save(Admin admin) {
        int insert = jdbcTemplate.update("insert into admin(username,password,age,school) values(?,?,?,?)",
                admin.getUsename(),admin.getPassword(),admin.getAge(),admin.getShcool());

        if (insert==1){
            return true;
        }else
        return false;
    }

    @Override
    public boolean update(Admin admin) {
        int update = jdbcTemplate.update("update admin set username=?,password=?,age=?,school=? where id=?",
                admin.getUsename(),admin.getPassword(),admin.getAge(),admin.getShcool(),admin.getId());
        if (update==1){
            return true;
        }else
            return false;
    }

    @Override
    public boolean delete(Integer id) {
        int delete= jdbcTemplate.update("delete from admin where id=?",id);
        if (delete==1){
            return true;
        }else
            return false;
    }
}
